package com.example.hello;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;


import android.util.Log;

public class DownloadPlugin extends CordovaPlugin {

	public static final String TAG = DownloadPlugin.class.getSimpleName();

	@Override
	public boolean execute(final String action, JSONArray args, final CallbackContext callbackContext)
	        throws JSONException {
		System.out.println("PluginDownload::execute");
		checkParam(action, args, callbackContext);
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				// 太小的文件，下载会很快结束，这个稍微大点
				String url = "https://codeload.github.com/apache/poi/zip/BUILD_BRANCH";
				downloadByUrl(url);
			}
		}).start();
		callbackContext.success("download start");
		return true;
	}

	/**
	 * just do some print
	 */
	private void checkParam(String action, JSONArray args, CallbackContext callbackContext) {
		StringBuilder sb = new StringBuilder();
		sb.append("checkParam\n");
		sb.append("action=" + action + "\n");
		sb.append("args=" + args.toString() + "\n");
		sb.append("callbackContext=" + callbackContext + "\n");
		System.out.println(sb.toString());
	}
	
	// 下载进度
	private void publish(final float per) {
		String event = "{'percent':" + per + "}";
		CordovaApp app = (CordovaApp) webView.getContext();
		app.sendToHtml(event);
	}
	
	// 下载信息
	private void publish(String info) {
		CordovaApp app = (CordovaApp) webView.getContext();
		app.sendToHtml(info);
	}
	
	// 下载完成 or 失败
	private void publish(boolean result){
		if(result){
			Log.i(TAG,"下载完成");
			publish("下载完成");
		}else{
			Log.i(TAG,"下载失败");
			publish("下载失败");
		}
	}

	// 下载文件
	private boolean downloadByUrl(String url) {
		try {
			URL aUrl = new URL(url);
			URLConnection conn = aUrl.openConnection();
			InputStream is = conn.getInputStream();
			int totalSize = conn.getContentLength();// 根据响应获取文件大小

			if (totalSize <= 0) {
				Log.e(TAG, "无法获知文件大小");
				publish("无法获知文件大小");
				return false;
			}
			if (is == null) {
				Log.e(TAG, "stream is null");
				publish("stream is null");
				return false;
			}

			byte buf[] = new byte[1024];
			int downLoadFileSize = 0;
			publish((float) downLoadFileSize / totalSize);

			do {
				// 循环读取
				int numread = is.read(buf);
				if (numread == -1) {
					break;
				}
				downLoadFileSize += numread;
				publish((float) downLoadFileSize / totalSize);
			} while (true);
			
			publish(true);
			
			is.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}
